package com.xkcoding.orm.mybatis.plus.config;

import com.baomidou.mybatisplus.core.enums.IEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * 枚举转换器
 * 最好是不用mybatis-plus的IEnum，不然耦合高
 * @Author lingNan
 * @Date 2022/7/22 18:09
 **/
public class EnumConverterFactory implements ConverterFactory<String, IEnum> {

    @Override
    public <T extends IEnum> Converter<String, T> getConverter(Class<T> targetType) {

        T[] enums = targetType.getEnumConstants();

        return source -> {
            for (T e : enums) {
                if (e.getValue().toString().equals(source)) {
                    return e;
                }
            }

            throw new IllegalArgumentException("枚举 value 不正确");
        };
    }

}
